<template>
  <div class="app-container">
    
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
         
          <el-form-item label="项目名称" prop="name">
            <el-input
              v-model="queryAttrParams.name"
              placeholder="请输入项目名称"
              clearable
              size="small"
              @keyup.enter.native="handleAttrQuery"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleAttrQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetAttrQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAttribute"
            >新增</el-button>
          </el-col> -->
          
          
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="attrLoading" :data="attributeList"  >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="项目名称" align="left" prop="name" width="300" />
          <el-table-column label="标签" align="left" prop="tags" width="300" />
          <el-table-column label="图片" align="center" prop="imgUrl" >
            <template slot-scope="scope">
              <el-image 
                style="width: 60px; height: auto"
                :src="scope.row.imgUrl" 
                :preview-src-list="[scope.row.imgUrl]">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center" prop="unit" />
          <el-table-column label="是否有数量" align="center" prop="hasNum" >
            <template slot-scope="scope">
              {{scope.row.hasNum == 1 ? '是' : '否'}}
            </template>
          </el-table-column>
          <!-- <el-table-column label="是否热门" align="center" prop="hot" >
            <template slot-scope="scope">
              {{scope.row.hot == 1 ? '是' : '否'}}
            </template>
          </el-table-column> -->
          <el-table-column label="指导价" align="center" prop="price" />
          <el-table-column label="成本价" align="center" prop="costPrice" />
          <el-table-column label="接单价" align="center" prop="receivePrice" />
          <el-table-column label="最低价" align="center" prop="floorPrice" />
          <el-table-column label="浮动价" align="center" prop="floatPrice" />
          <el-table-column label="销量" align="center" prop="saleNum" />
          <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleAttrUpdate(scope.row)"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleAttrDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column> -->
        </el-table>
        
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryAttrParams.pageNum"
          :limit.sync="queryAttrParams.pageSize"
          @pagination="getAttributeList"
        />
  
    <!-- 添加或修改服务分类参数对话框 -->
    <el-dialog title="服务类目属性管理" :visible.sync="attrOpen" width="60%" append-to-body>
      <el-form ref="attrform" :model="attrform"  label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
             <el-form-item label="项目名称" prop="name">
              <el-input v-model="attrform.name" placeholder="请输入项目" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item :label="item.name" v-for="item in attrCategorySpecList" v-bind:key="item.id" style="margin-bottom: 10px;">
              <el-radio v-model="item.value" :label="v.value" border  size="small" v-for="v in item.specValueList" v-bind:key="v.id">{{v.value}}</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="16">
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="单位" prop="unit">
                  <el-select v-model="attrform.unit" placeholder="请选择单位" clearable filterable  size="small">
                    <el-option
                      v-for="dict in unitOptions"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="接单人数" prop="limitNum">
                  <el-input v-model="attrform.limitNum" placeholder="请输入接单人数限制" />
                </el-form-item>
              </el-col>
            </el-row>
             
            
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="指导价" prop="price">
                  <el-input v-model="attrform.price" placeholder="请输入指导价" >
                    <template slot="append">￥</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="是否热门" prop="hot">
                  <el-radio v-model="attrform.hot" label="1" border  size="small">是</el-radio>
                  <el-radio v-model="attrform.hot" label="0" border  size="small">否</el-radio>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="是否有数量" prop="hasNum">
                  <el-radio v-model="attrform.hasNum" label="1" border  size="small">是</el-radio>
                  <el-radio v-model="attrform.hasNum" label="0" border  size="small">否</el-radio>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="接单限制" prop="limitType">
                  <el-radio v-model="attrform.limitType" label="0" border  size="small">无</el-radio>
                  <el-radio v-model="attrform.limitType" label="1" border  size="small">公司</el-radio>
                  <el-radio v-model="attrform.limitType" label="2" border  size="small">个人</el-radio>
                  <el-radio v-model="attrform.limitType" label="3" border  size="small">兼职</el-radio>
                </el-form-item>
              </el-col>
            </el-row>
            
          </el-col>
          <el-col :span="8">
            <el-form-item label="图片" prop="imgUrl">
              <imageUpload v-model="attrform.imgUrl"/>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="详情">
              <editor v-model="attrform.detail" :min-height="192" :height="200"/>
            </el-form-item>
          </el-col>
        </el-row>
       
        
      </el-form>
      <div slot="footer"  class="dialog-footer" >
        <el-button type="primary" @click="submitAttrForm">确 定</el-button>
        <el-button @click="cancelAttr">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, delCategory, addCategory, updateCategory, exportCategory } from "@/api/business/category";
import { listHotAttribute, delAttribute, addAttribute, updateAttribute, exportAttribute } from "@/api/business/attribute";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ImageUpload from '@/components/ImageUpload';
import Editor from '@/components/Editor';
export default {
  name: "Category",
  components: {
    ImageUpload,
    Treeselect,
    Editor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      attrLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 服务类目表格数据
      categoryList: [],
      attributeList: [],
      // 服务类目树选项
      categoryOptions: [],
      // 分类-规格属性表格数据
      categorySpecList: [],
      categorySpecValueList: [],
      // 选中数组
      ids: [],
      currentSpecRow: null,
      // 子表选中数据
      checkedCategorySpec: [],
      // 子表选中数据
      checkedCategoryCert: [],
      // 分类-证书关联表格数据
      categoryCertList: [],
      attrCategorySpecList: [],
      attrSpecValueList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      total: 0,
      attrOpen: false,
      unitOptions: [],
      certOptions: [],
      // 查询参数
      queryParams: {
        name: null,
        keywords: null,
        description: null,
        parentId: null,
        level: null,
      },
      queryAttrParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        name: null,
        value: null
      },
      
      clickRow: null,
      // 表单参数
      form: {},
      attrform: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "类目名称不能为空", trigger: "blur" }
        ],
        
      }
    };
  },
  created() {
    this.getAttributeList();
    this.getDicts("tb_unit_type").then(response => {
      this.unitOptions = response.data;
    });
    this.getDicts("tb_cert_type").then(response => {
      this.certOptions = response.data;
    });
  },
  methods: {
    /** 查询服务类目列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = this.handleTree(response.data, "id", "parentId");
        this.loading = false;
      });
    },
    /** 查询服务分类参数列表 */
    getAttributeList() {
      
      this.attrLoading = true;
      listHotAttribute(this.queryAttrParams).then(response => {
        this.attributeList = response.rows;
        this.total = response.total;
        this.attrLoading = false;
      });
    },
    /** 转换服务类目数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
	/** 查询服务类目下拉树结构 */
    getTreeselect() {
      listCategory().then(response => {
        this.categoryOptions = [];
        const data = { id: 0, name: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.categoryOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        keywords: null,
        description: null,
        parentId: null,
        iconUrl: null,
        picUrl: null,
        level: null,
        sort: null
      };
      this.categorySpecValueList = [];
      this.categorySpecList = [];
      this.categoryCertList = [];
      this.resetForm("form");
    },
    // 表单重置
    resetAttr() {
      this.attrform = {
        id: null,
        name: null,
        value: null,
        unit: null,
        price: null,
        hasNum: '1',
        detail: null,
        limitUser: '0',
        hot: '0'
      };
      this.resetForm("attrform");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 搜索按钮操作 */
    handleAttrQuery() {
      this.getAttributeList();
    },
    /** 搜索按钮操作 */
    resetAttrQuery() {
      this.queryAttrParams.name = "";
      this.getAttributeList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAttribute(){
      if (!this.clickRow) {
        this.msgError("请先选择服务分类");
        return;
      }
      this.reset();
      this.attrOpen = true;
      this.queryAttrParams.categoryId = this.clickRow.id;
      this.attrform = {
        categoryId: this.clickRow.id,
        id: null,
        name: null,
        value: null,
        unit: null,
        detail: null,
        price: null,
        hasNum: '1',
        hot: '0',
        limitUser: '0'
      };
      getCategory(this.clickRow.id).then(response => {

        this.attrCategorySpecList = response.data.categorySpecList;
        
      });
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.id;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加服务类目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.id;
      }
      getCategory(row.id).then(response => {
        this.form = response.data;
        this.categorySpecList = this.form.categorySpecList;
        this.categoryCertList = this.form.categoryCertList;
        this.open = true;
        this.title = "修改服务类目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.categorySpecList = this.categorySpecList;
          this.form.categoryCertList = this.categoryCertList;
          if (this.form.id != null) {
            updateCategory(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {            
            addCategory(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除服务类目编号为"' + row.id + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCategory(row.id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
   
    /** 提交按钮 */
    submitAttrForm() {
      console.log(this.attrCategorySpecList)
      this.$refs["attrform"].validate(valid => {
        if (valid) {
          this.attrform.attrSpecValueList = this.attrCategorySpecList.map(a => {
            return {
              spec: a.name,
              value: a.value
            }
          });
          if (this.attrform.id != null) {
            updateAttribute(this.attrform).then(response => {
              this.msgSuccess("修改成功");
              this.attrOpen = false;
              this.getAttributeList();
              this.resetAttr();
            });
          } else {
            addAttribute(this.attrform).then(response => {
              this.msgSuccess("新增成功");
              this.attrOpen = false;              
              this.getAttributeList();
              this.resetAttr();
              
            });
          }
        }
      });
    },
    /** 修改按钮操作 */
    handleAttrUpdate(row) {     
      this.attrform = row;  
      this.attrOpen = true;  
      getCategory(row.categoryId).then(response => {
        let specList = response.data.categorySpecList;
        specList.forEach(a => {
          let val = row.attrSpecValueList.find(b => b.spec == a.name);
          a.value = val?.value;
        });
        this.attrCategorySpecList = specList;
        console.log(row.attrSpecValueList)
        console.log(this.attrCategorySpecList)
      });  
    },
    /** 删除按钮操作 */
    handleAttrDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除服务分类参数编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAttribute(ids);
        }).then(() => {
          this.getAttributeList();
          this.msgSuccess("删除成功");
        })
    },
    // 取消按钮
    cancelAttr() {
      this.attrOpen = false;
      this.reset();
    },
    handleCategoryRowClick(row) {
      this.clickRow = row;
      this.getAttributeList();
    },
    /** 分类-规格属性序号 */
    rowCategorySpecIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 分类-规格属性添加按钮操作 */
    handleAddCategorySpec() {
      let obj = {};
      obj.name = "";
      obj.specValueList = [];
      this.categorySpecList.push(obj);
      this.categorySpecValueList = [];
    },
    /** 分类-规格属性删除按钮操作 */
    handleDeleteCategorySpec() {
      if (this.checkedCategorySpec.length == 0) {
        this.$alert("请先选择要删除的分类-规格属性数据", "提示", { confirmButtonText: "确定", });
      } else {
        this.categorySpecList = this.categorySpecList.filter(a=>a != this.checkedCategorySpec[0]);
      }
    },
    /** 单选框选中数据 */
    handleCategorySpecSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.categorySpec.clearSelection();
        this.$refs.categorySpec.toggleRowSelection(selection.pop());
      } else {
        this.checkedCategorySpec = selection;
      }
    },
    /** 分类-证书关联序号 */
    rowCategoryCertIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 分类-证书关联添加按钮操作 */
    handleAddCategoryCert() {
      let obj = {};
      obj.certName = "";
      this.categoryCertList.push(obj);
    },
    /** 分类-证书关联删除按钮操作 */
    handleDeleteCategoryCert() {
      if (this.checkedCategoryCert.length == 0) {
        this.$alert("请先选择要删除的分类-证书关联数据", "提示", { confirmButtonText: "确定", });
      } else {
        this.categoryCertList = this.categoryCertList.filter(a=>a != this.checkedCategoryCert[0]);
      }
    },
    /** 单选框选中数据 */
    handleCategoryCertSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.categoryCert.clearSelection();
        this.$refs.categoryCert.toggleRowSelection(selection.pop());
      } else {
        this.checkedCategoryCert = selection;
      }
    },
    addNewSpecValueRow(row){
      console.log(row)
      this.currentSpecRow = row;
      if (row.specValueList && row.specValueList.length > 0) {
        this.categorySpecValueList = row.specValueList;
      } else {
        this.categorySpecValueList = [{
          value: ""
        }];
        row.specValueList = this.categorySpecValueList;
        
      }
    },
    
    handleSpecValueAdd(row){
      this.categorySpecValueList.push({
        value: ""
      });
      this.currentSpecRow.specValueList = this.categorySpecValueList;
    },
    handleSpecValueDelete(row){
      this.categorySpecValueList = this.categorySpecValueList.filter(a=>a !=row);
      this.currentSpecRow.specValueList = this.categorySpecValueList;
    },
  }
};
</script>
<style scoped>
  .el-button + .el-button {
      margin-left: 4px;
  }
  .el-radio{
    margin-right: 0px;
  }
</style>
